import numpy as np
import pandas as pd
from django.http import HttpResponse
from sklearn.linear_model import LinearRegression, LogisticRegression, BayesianRidge
from sklearn.model_selection import train_test_split, GridSearchCV, ShuffleSplit
from rest_framework.response import Response
from sklearn.neighbors import KNeighborsRegressor
from sklearn.svm import SVR, SVC

from common.http_request import HttpRequest


class CommonServer(HttpRequest):

    @classmethod
    def export_to_excel(cls, request):
        # 创建一个Pandas DataFrame
        data = request.data

        df = pd.DataFrame.from_dict(data)
        # 导出文件名称
        filename = 'file.csv'

        # 使用Pandas Excel写入器导出DataFrame
        response = HttpResponse(df.to_csv(index=False), content_type='text/csv; charset=utf-8')
        response['Content-Disposition'] = f'attachment; filename="{filename}"'

        return response

    # 线性回归预测
    def predict_data(self, request):
        X = np.array(request.data['X'], dtype=float)
        Y = np.array(request.data['Y'], dtype=float)
        pred_date = request.data['predDate']

        linearRegressionModel = self.linearRegressionModel(X, Y)
        if linearRegressionModel['score'] > 0.8:
            pred = linearRegressionModel['regressor'].predict([[pred_date]])

            a, b = linearRegressionModel['regressor'].coef_, linearRegressionModel['regressor'].intercept_

            data = {
                'sq': 'y = {:.2f}x + {:.2f}'.format(a[0], b),
                'score': linearRegressionModel['score'],
                'pred': pred
            }
            return Response(data)

        data = {
            'code': 500,
            'msg': '未找到合适的预测模型'
        }

        return Response(data)

    # 线性预测模型
    @classmethod
    def linearRegressionModel(cls, x, y):
        X = []
        for i in range(len(x)):
            X.append([x[i][0]])
        X_train, X_test, Y_train, Y_test = train_test_split(X, y, test_size=0.2, random_state=7)
        regressor = LinearRegression()

        regressor.fit(X_train, Y_train)
        score = regressor.score(X_train, Y_train)

        return {
            'score': score,
            'regressor': regressor
        }

    # 贝叶斯回归预测模型
    @classmethod
    def BayesianRidgeModel(cls, x, y):
        reg = BayesianRidge()
        reg.fit(x, y)
        score = reg.score(x, y)

        return {
            'score': np.float64(score).astype(int),
            'regressor': reg
        }
